<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <!-- <div class="head-container">
          <el-input
            v-model="dictType"
            placeholder="请输入分类名称"
            clearable
            prefix-icon="Search"
            style="margin-bottom: 20px"
          />
        </div> -->
        <div class="add">
          <el-button @click="handleAddLevel1" style="width: 100%"
            >添加一级分类</el-button
          >
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="{ label: 'dictName', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :default-expanded-keys="defaultExpandIds"
            ref="deptTreeRef"
            node-key="id"
            highlight-current
            :default-expand-all="false"
            @node-click="handleNodeClick"
            @node-expand="handleNodeExpand"
            @node-collapse="handleNodeCollapse"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
                <span class="edit">
                  <!-- <el-tooltip content="添加分类" placement="top">
                    <a @click.stop="append(data)">
                      <el-icon><Plus /></el-icon>
                    </a>
                  </el-tooltip> -->
                  <el-tooltip content="编辑" placement="top">
                    <a style="margin-left: 8px" @click.stop="handelEdit(data)">
                      <el-icon><Edit /></el-icon>
                    </a>
                  </el-tooltip>
                  <el-tooltip content="删除" placement="top">
                    <a
                      style="margin-left: 8px"
                      @click.stop="handelDelClass(data)"
                    >
                      <el-icon><DeleteFilled /></el-icon>
                    </a>
                  </el-tooltip>
                </span>
              </span>
            </template>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <div class="search">
          <!-- 搜索表单 -->
          <el-form :model="serchForm" ref="formRef">
            <el-row :gutter="20">
              <el-col :span="8"
                ><div class="grid-content ep-bg-purple" />
                <el-form-item label="联系人" prop="account">
                  <el-input
                    v-model="serchForm.model.tenantContact"
                    placeholder="请输入联系人"
                    style="width: 200px"
                  ></el-input> </el-form-item
              ></el-col>

              <el-col :span="8"
                ><div class="grid-content ep-bg-purple" />
                <el-form-item label="账号" prop="account">
                  <el-input
                    v-model="serchForm.model.account"
                    placeholder="账号"
                    style="width: 200px"
                  ></el-input> </el-form-item
              ></el-col>

              <el-col :span="8">
                <el-form-item label="授权状态">
                  <el-select
                    v-model="serchForm.model.status"
                    placeholder="请选择"
                    size="mini"
                  >
                    <el-option label="禁用" :value="0"></el-option>
                    <el-option label="正常" :value="1"></el-option>
                    <el-option label="待审核" :value="2"></el-option>
                    <el-option label="审批通过" :value="3"></el-option>
                    <el-option label="审批驳回不通过" :value="4"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="8"
            ><div class="grid-content ep-bg-purple" />
            <el-form-item label="创建时间" prop="createAt">
              <el-date-picker
                v-model="serchForm.createAt"
                type="daterange"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间" /></el-form-item
          ></el-col> -->
            </el-row>
          </el-form>
          <!--重置 搜搜按钮 -->
          <div class="btns">
            <el-button icon="Refresh" @click="handleResetClick">重置</el-button>
            <el-button type="primary" icon="Search" @click="handleQueryClick"
              >查询</el-button
            >
            <!-- <el-button type="primary" @click="dialogFormVisible = true"
          ><el-icon><Upload /></el-icon>新增</el-button
        > -->
          </div>
        </div>

        <!-- 表单 -->
        <div class="content">
          <div class="content">
            <div class="table">
              <el-table :data="dataList" border style="width: 100%">
                <el-table-column
                  align="center"
                  width="100"
                  prop="name"
                  label="企业LOGO "
                >
                  <template #default="scope">
                    <el-image
                      style="width: 50px; height: 50px"
                      preview-teleported
                      :src="scope.row.logoUrl"
                      :zoom-rate="1.2"
                      :max-scale="7"
                      :min-scale="0.2"
                      :preview-src-list="[scope.row.logoUrl]"
                      :initial-index="4"
                      fit="cover"
                    />
                  </template>
                </el-table-column>

                <el-table-column
                  align="center"
                  prop="tenantName"
                  label="企业名称"
                  show-overflow-tooltip
                  width="120"
                />
                <el-table-column align="center" prop="account" label="账号 " />

                <!-- <el-table-column
                  align="center"
                  prop="businessType"
                  label="企业类型"
                  show-overflow-tooltip
                  width="120"
                /> -->
                <el-table-column
                  align="center"
                  prop="duties"
                  label="申请人职务"
                  show-overflow-tooltip
                  width="120"
                />

                <el-table-column align="center" label="状态操作" width="100">
                  <template #default="scope">
                    <el-switch
                      v-model="scope.row.status"
                      :active-value="1"
                      :inactive-value="0"
                      @click="changeShow(scope.row)"
                    />
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="requirement" label="状态">
                  <template #default="scope">
                    <el-tag
                      v-if="scope.row.status == 0"
                      type="danger"
                      size="small"
                    >
                      禁用
                    </el-tag>
                    <el-tag
                      v-if="scope.row.status == 1"
                      type="success"
                      size="small"
                    >
                      正常
                    </el-tag>
                    <el-tag
                      v-if="scope.row.status == 2"
                      type="danger"
                      size="small"
                    >
                      待审核
                    </el-tag>
                    <el-tag v-if="scope.row.status == 3" size="small">
                      审批通过
                    </el-tag>
                    <el-tag
                      v-if="scope.row.status == 4"
                      type="danger"
                      size="small"
                    >
                      <el-tooltip
                        class="box-item"
                        effect="dark"
                        :content="scope.row.remark"
                        placement="top-start"
                      >
                        审批驳回不通过
                      </el-tooltip>
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  prop="tenantContact"
                  label="联系人"
                  show-overflow-tooltip
                  width="100"
                />
                <!-- <el-table-column
              align="center"
              prop="createTime"
              label="申请时间"
              width="200"
            >
              <template #default="scope">
                {{ formatDateTime(scope.row.createTime) }}
              </template>
            </el-table-column> -->

                <el-table-column
                  align="center"
                  prop="tenantEmail"
                  show-overflow-tooltip
                  label="联系邮箱"
                />
                <el-table-column
                  align="center"
                  prop="landline"
                  label="座机"
                  width="180"
                />

                <el-table-column
                  align="center"
                  prop="tenantTel"
                  label="联系电话"
                  width="120"
                />

                <el-table-column align="center" label="操作" width="100">
                  <template #default="scope">
                    <el-row>
                      <el-button
                        size="small"
                        type="primary"
                        text
                        @click="resetPassword(scope.row)"
                        >重置密码</el-button
                      >
                    </el-row>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="pagination">
              <el-pagination
                v-model:current-page="serchForm.current"
                v-model:page-size="serchForm.size"
                :page-sizes="[10, 20, 30]"
                layout="->,total,sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 添加分类log框 -->
    <el-dialog
      :title="`${classForm.id ? '编辑' : '新增'}分类`"
      v-model="classdialogVisible"
      width="30%"
      @close="beforeClose1"
    >
      <el-form
        :model="classForm"
        ref="ruleFormRef"
        label-width="120px"
        :rules="rules1"
      >
        <el-form-item label="分类" prop="dictName">
          <el-input v-model="classForm.dictName" style="width: 300px" />
        </el-form-item>

        <el-form-item label="排序" prop="dictSequence">
          <el-input
            v-model.number="classForm.dictSequence"
            style="width: 300px"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="classdialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handelNewClass"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 对话框 -->
    <el-dialog v-model="dialogFormVisible" title="新建">
      <el-form :model="form" ref="formEl">
        <el-form-item label="应用名称" label-width="110" prop="appName">
          <el-input
            v-model="form.appName"
            autocomplete="off"
            placeholder="请输入应用名称"
          />
        </el-form-item>
        <el-form-item label="购买账号" label-width="110" prop="purchaseAccount">
          <el-input
            v-model="form.purchaseAccount"
            autocomplete="off"
            placeholder="请输入购买账号"
          />
        </el-form-item>
        <el-form-item label="购买账号名称" label-width="110" prop="accountName">
          <el-input
            v-model="form.accountName"
            autocomplete="off"
            placeholder="请输入购买账号名称"
          />
        </el-form-item>
        <el-form-item label="成交时间" label-width="110" prop="transactionTime">
          <el-date-picker
            v-model="form.transactionTime"
            type="datetime"
            placeholder="成交时间"
            format="YYYY/MM/DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="使用期限" label-width="110" prop="usagePeriod">
          <el-input v-model="form.usagePeriod" autocomplete="off" />
        </el-form-item>
        <el-form-item label="到期时间" label-width="110" prop="expirationTime">
          <el-date-picker
            v-model="form.expirationTime"
            type="datetime"
            placeholder="到期时间"
            format="YYYY/MM/DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="授权状态" label-width="110" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import { formatDateTime } from "@/utils/index.js";
import {
  queryListRequest,
  updateStatusRequest,
  updatePasswordRequest,
} from "@/api/frontUser/firmUser.js";

import {
  getDickAllTreeListRequest,
  insertModelType,
  updateModelType,
  deleteModelType,
} from "@/api/buildlibrary";

import { ElMessage, ElMessageBox } from "element-plus";

const total = ref(0);

const serchForm = reactive({
  current: 1,
  size: 10,
  model: {},
});

onMounted(() => {
  getList();

  // 树形菜单获取
  getTreeList();
});

// 列表数据
const dataList = ref([]);
async function getList() {
  const res = await queryListRequest(serchForm);
  console.log(res);
  dataList.value = res.data.records;
  total.value = res.data.total;
}

//重置
function handleResetClick() {
  console.log("reset");
  serchForm.current = 1;
  serchForm.size = 10;
  serchForm.model = {};
  getList();
}
//查询操作
function handleQueryClick() {
  serchForm.current = 1;
  console.log("handleQueryClick", serchForm);
  getList();
}

//分页器size事件
const handleSizeChange = (size) => {
  serchForm.size = size;
  getList();
};
//分页器current事件
const handleCurrentChange = (current) => {
  serchForm.current = current;
  getList();
};

//状态改变事件
async function changeShow(row) {
  const { status, id } = row;

  let data = {
    id,
    status,
  };
  const res = await updateStatusRequest(data);
  console.log(res);
  if (res.code === 200) {
    ElMessage.success("状态修改成功！");
    getList();
  }
}

//重置密码
const resetPassword = (row) => {
  const { id } = row;

  ElMessageBox.confirm(
    `确定重置账户为:${row.account}密码吗？重置后的密码为zhongjian+手机号后四位`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(async () => {
    const res = await updatePasswordRequest(id);
    console.log(res);
    if (res.data) {
      ElMessage.success("密码重置成功！");
      getList();
    }
  });
};

//左侧菜单相关
const dictType = ref("");
const deptOptions = ref([]);

//获取左侧树形列表
const getTreeList = async () => {
  const res = await getDickAllTreeListRequest({ level: 5, dictType: 5 });
  deptOptions.value = res.data;
  console.log(res);
};

//添加分类的表单
let classForm = reactive({
  dictName: "", //分类名称
  dictType: "5", //dictType
  parentId: 0, //父ID
  dictStatus: 0, //状态
  dictSequence: 0, //排序
  dictValue: 0,
});
//添加分类的显示隐藏
const classdialogVisible = ref(false);
const ruleFormRef = ref(null);

const parentDictValue = ref(null);

//新建顶级分类
const handleAddLevel1 = () => {
  classdialogVisible.value = true;
  classForm.parentId = 0;
  parentDictValue.value = null;
};

//分类规则
const rules1 = reactive({
  dictName: [{ required: true, message: "请输入分类", trigger: "blur" }],
});
//新建分类方法
const append = (row) => {
  classdialogVisible.value = true;
  console.log(row);
  classForm.dictSequence = row.children.length + 1;
  parentDictValue.value = row.dictValue;
  classForm.dictType = "5";
  classForm.parentId = row.id;
};

//新建分类提交表单确认方法
const handelNewClass = () => {
  ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      let data = {
        ...classForm,
      };

      // return;
      let fun = data.id ? updateModelType : insertModelType;
      const { code } = await fun(data);
      if (code === 200) {
        ElMessage.success(`${data.id ? "编辑" : "添加"}成功`);
        classdialogVisible.value = false;
        parentDictValue.value = null;
        getTreeList();
      } else {
        ElMessage.error("服务故障，稍后再试");
        parentDictValue.value = null;
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

let isEdit = ref(false); //是否编辑
//编辑分类表单事件
const handelEdit = (row) => {
  console.log(row);
  isEdit.value = true;
  classdialogVisible.value = true;
  classForm.dictName = row.dictName; //分类名称
  classForm.parentId = row.parentId; //父级名称
  classForm.dictType = "5"; //类型
  classForm.id = row.id; //id
  classForm.dictSequence = row.dictSequence; //排序
};

//删除模型分类事件
const handelDelClass = (row) => {
  console.log(row);
  let id = row.id;
  // return;
  ElMessageBox.confirm("你确定要删除此分类吗?", "警告", {
    confirmButtonText: "确认删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const { code } = await deleteModelType({ ids: [id] });
        if (code === 200) {
          ElMessage.success(`删除成功`);
          getTreeList();
        } else {
          ElMessage.error(`服务器故障，稍后再试`);
        }
      } catch (error) {}
    })
    .catch(() => {});
};

//关闭dlog回调
const beforeClose1 = () => {
  isEdit.value = false; //退出编辑模式
  ruleFormRef.value.resetFields();
  console.log(1123123);
  //数据初始化
  classForm = reactive({
    dictName: "",
    dictValue: 0,
    dictType: "5",
    parentId: 0,
    dictStatus: 0,
    dictSequence: 0,
  });
};

function handleNodeClick(nodeData) {
  console.log(nodeData);
  let id = nodeData.id;
  serchForm.model.businessType = id;
  //请求数据
  // searchQuery.model.classifyId = nodeData.id;
  // getModelList();
  getList();
}
</script>
<style lang="scss" scoped>
label {
  font-weight: 0 !important;
}
.search {
  background-color: #fff;
  padding: 20px;
}
.search .btns {
  text-align: right;
  padding: 0 50px 10px 0;
}
.pagination {
  margin-top: 14px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  .edit {
    display: none;
  }
  &:hover {
    // display: block;
    // background-color: red;
    .edit {
      display: block;
    }
  }
}
</style>
